<template>
  <div class="queryform-container">
    <a-form ref="queryFormRef" :model="queryForm" layout="inline">
      <a-form-item autocomplete="off"
                   label="用户名"
                   name="username">
        <a-input v-model:value="queryForm.username" allow-clear/>
      </a-form-item>
      <a-form-item autocomplete="off"
                   label="角色"
                   name="roleId">
        <a-select allow-clear style="width:200px;"
                  v-model:value="queryForm.roleId"
                  mode="tags"
                  placeholder=""
        >
          <a-select-option v-for="role in roleList" :value="role.roleCode">{{ role.roleName }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleQuery">查询</a-button>
        <a-button type="primary" class="split-button" @click="handleReset">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
  <a-table rowKey="id" :row-selection="rowSelection" :data-source="sysUserList" :columns="columns">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <a-button @click="openRoleDiag(record)">设置角色</a-button>
      </template>
    </template>
  </a-table>
  <a-modal v-model:visible="showEditingDiag" title="设置用户角色" @ok="handleSave">
    <a-form ref="addForm" :model="userRoleForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }" autocomplete="off">
      <a-form-item style="display: none;"
                   label="id"
                   name="id">
        <a-input v-model:value="userRoleForm.userCode"/>
      </a-form-item>
      <a-form-item
          label="角色"
          name="roleCodes"
          :rules="[{ required: true, message: '请选择一个角色!' }]"
      >
        <a-select allow-clear style="width:200px;"
                  v-model:value="userRoleForm.roleCodes"
                  mode="tags"
                  placeholder=""
        >
          <a-select-option v-for="role in roleList" :value="role.roleCode">
            {{ role.roleName }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import request from "@/util/request.js";
import {message} from 'ant-design-vue';
import {showLoading,hideLoading} from "@/util/util.js";

export default {
  data() {
    return {
      showAddModel: false,
      sysUserList: [],
      roleList: [],
      columns: [{
        title: '用户名',
        dataIndex: 'username',
        key: 'username'
      },{
        title: '用户昵称',
        dataIndex: 'nickname',
        key: 'nickname'
      }, {
        title: '操作',
        dataIndex: 'action',
        key: 'action'
      }],
      userRoleForm: {},
      selectedRows: [],
      singleSelect: false,
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
          this.selectedRows = selectedRows
          this.singleSelect = this.selectedRows && this.selectedRows.length === 1;
        },
        // getCheckboxProps: record => ({
        //   disabled: record.name === 'Disabled User',
        //   // Column configuration not to be checked
        //   name: record.name,
        // }),
      },
      queryForm: {username: null},
      editingRow: null,
      showEditingDiag: false,
    }
  },
  mounted() {
    this.query();
    //加载所有的角色
    request({
      method: 'post',
      url: '/api/system/sysRole/list',
      data: {},
    }).then((res) => {
      this.roleList = res.data
    })
  },
  methods: {
    async loadAllRoleCodeByUserCode(userCode) {
      let res = await request({
        method: 'get',
        url: '/api/system/sysUserRole/queryRoleCodeByUserCode?userCode=' + userCode,
      })
      let roleCodeList = res.data
      return roleCodeList
    },
    async openRoleDiag(row) {
      this.editingRow = row;
      this.showEditingDiag = true;
      this.userRoleForm.roleCodes = [];
      //加载当前用户的所有的角色codes
      let roleCodeList = await this.loadAllRoleCodeByUserCode(row.userCode);
      this.userRoleForm.roleCodes = roleCodeList;
    },
    handleQuery() {
      this.query(this.queryForm)
    },
    handleReset(){
      this.$refs.queryFormRef.resetFields()
    },
    query(param) {
      showLoading()
      request({
        method: 'post',
        url: '/api/system/sysUser/query',
        data: param || {}
      }).then((res) => {
        hideLoading()
        this.sysUserList = res.data
      })
    },
    handleOpenAddModel(editing) {
      this.showAddModel = true
      this.sysUserForm = {}
      if (editing) {
        this.$nextTick(() => {
              //加载明细
              let selectedRow = this.selectedRows[0];
              this.sysUserForm = {...selectedRow};
            }
        )
      }
    },
    handleSave() {
      let addForm = this.$refs.addForm;
      addForm.validate().then((res) => {
        let data = {
          userCode: this.editingRow.userCode,
          roleCodeList: res.roleCodes,
        }
        showLoading()
        request({
          method: 'post',
          url: '/api/system/sysUserRole/saveOrUpdate',
          data: data
        }).then((res) => {
          hideLoading()
          if (res.code === 200) {
            this.showEditingDiag = false;
            message.success("保存成功")
            this.query();
          } else {
            message.error("操作失败" + res.errMsg)
          }
        })
      }).catch(() => {
        hideLoading()
      })
    },
  }
}
</script>
